<template>
  <el-dialog v-model="dialogVisible" :title="title" width="70%" @close="handleClose">
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px" class="mt-4">
      <!-- 基本信息 -->
      <div class="mb-6">
        <div class="text-lg font-medium text-gray-700 mb-4">基本信息</div>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="任务下达时间" prop="taskReceive_time">
              <el-date-picker v-model="formData.taskReceive_time" type="datetime" value-format="x"
                placeholder="选择任务接收时间" disabled />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="接收人" prop="assigneerId">
              <el-input v-model="assigneerName" disabled />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="接收时间" prop="taskReceive_time">
              <el-date-picker v-model="formData.taskReceive_time" type="datetime" value-format="x"
                placeholder="选择任务接收时间" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="任务开始时间" prop="taskStartTime">
              <el-date-picker v-model="formData.taskStartTime" type="datetime" value-format="x" placeholder="选择开始时间"
                @change="calculateWorkHours" />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="任务结束时间" prop="taskEndTime">
              <el-date-picker v-model="formData.taskEndTime" type="datetime" value-format="x" placeholder="选择结束时间"
                @change="calculateWorkHours" />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="工时(分钟)" prop="taskExecutionDuration">
              <div class="flex items-center">
                <el-input-number v-model="formData.taskExecutionDuration" :min="0" style="width: 100%"
                  placeholder="自动计算" :disabled="true" />
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="保养人" prop="assigneerIds">
              <el-select clearable multiple filterable v-model="formData.assigneerIds" placeholder="请选择保养人">
                <el-option v-for="dict in maintainerList" :key="dict.id" :label="dict.nickname" :value="dict.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注" prop="description">
              <el-input v-model="formData.description" type="textarea" :rows="2" placeholder="请输入备注"
                style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 保养项列表 -->
      <div class="mb-6">
        <div class="flex justify-between items-center mb-4">
          <div class="text-lg font-medium text-gray-700">保养项列表</div>
          <div class="flex items-center">
            <el-checkbox v-model="selectAll" @change="handleSelectAllChange" class="mr-4">
              全选
            </el-checkbox>
            <div class="text-sm text-gray-500">
              已完成 {{ completedItemsCount }} / {{ upkeepItems.length }} 项
            </div>
          </div>
        </div>
        <el-table :data="upkeepItems" border style="width: 100%"
          :header-cell-style="{ background: '#e6f7ef', color: '#008c46' }">
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column prop="itemName" label="保养项名称" width="200" />
          <el-table-column prop="itemCode" label="保养项编码" width="150" />
          <el-table-column label="保养项描述" min-width="300">
            <template #default="scope">
              <div v-html="scope.row.itemDescription"></div>
            </template>
          </el-table-column>
          <el-table-column label="是否完成" width="100" align="center">
            <template #default="scope">
              <el-checkbox v-model="scope.row.isCompleted" @change="handleItemCompleteChange(scope.row)" />
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">提交</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import * as UserApi from '@/api/system/user'
import { getUserProfile } from '@/api/system/user/profile'
import type { UserVO } from '@/api/system/user'
import { UpkeepTaskApi, UpkeepTaskWorkReport } from '@/api/mold/upkeeptask'
import { UpkeepCategoryApi } from '@/api/mold/upkeepcategory'

interface UpkeepItem {
  id: number
  itemName: string
  itemCode: string
  itemDescription: string
  isCompleted: boolean
}

interface FormDataType {
  id: number
  assigneerId: string
  taskReceive_time: string
  jobStartTime: string
  taskStartTime: string
  taskEndTime: string
  taskExecutionDuration: number
  assigneerIds: number[]
  description: string
  isCompleted: boolean
}

// 定义组件的 props
const props = withDefaults(defineProps<{
  title?: string
}>(), {
  title: '报工'
})

// 定义组件的 emits
const emit = defineEmits<{
  (e: 'success'): void
}>()

// 表单数据
const formData = reactive<FormDataType>({
  id: 0,
  assigneerId: '',
  taskReceive_time: '',
  jobStartTime: '',
  taskStartTime: '',
  taskEndTime: '',
  taskExecutionDuration: 0,
  assigneerIds: [],
  description: '',
  isCompleted: false
})

// 接收人名称（用于显示）
const assigneerName = ref('')

// 保养项列表
const upkeepItems = ref<UpkeepItem[]>([])

// 保养人员列表
const maintainerList = ref<UserVO[]>([])

// 表单验证规则
const rules = {
  taskStartTime: [
    { required: true, message: '请选择任务开始时间', trigger: 'blur' }
  ],
  taskEndTime: [
    { required: true, message: '请选择任务结束时间', trigger: 'blur' }
  ],
  assigneerIds: [
    { required: true, message: '请选择保养人员', trigger: 'change' }
  ]
}

// 表单引用
const formRef = ref()
const taskId = ref<number>(0)

// 对话框状态
const dialogVisible = ref(false)
const submitting = ref(false)

const selectAll = ref(false)


// 修改计算属性 completedItemsCount
const completedItemsCount = computed(() => {
  return upkeepItems.value.filter(item => item.isCompleted).length
})


// 添加全选变更处理函数
const handleSelectAllChange = (checked: boolean) => {
  upkeepItems.value.forEach(item => {
    item.isCompleted = checked
  })
  // 同步更新 formData.isCompleted 状态
  formData.isCompleted = checked && upkeepItems.value.length > 0
}



// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

// 重置表单
const resetForm = () => {
  formData.id = 0
  formData.assigneerId = ''
  formData.taskReceive_time = ''
  formData.jobStartTime = ''
  formData.taskStartTime = ''
  formData.taskEndTime = ''
  formData.taskExecutionDuration = 0
  formData.assigneerIds = []
  formData.description = ''
  formData.isCompleted = false
  assigneerName.value = ''
  upkeepItems.value = []
  selectAll.value = false
}

// 计算工时
const calculateWorkHours = () => {
  if (formData.taskStartTime && formData.taskEndTime) {
    const startTime = new Date(parseInt(formData.taskStartTime)).getTime()
    const endTime = new Date(parseInt(formData.taskEndTime)).getTime()

    if (startTime >= endTime) {
      ElMessage.warning('任务结束时间必须任务开始时间')
      formData.taskExecutionDuration = 0
      return
    }

    // 计算分钟数
    const minutes = Math.floor((endTime - startTime) / (1000 * 60))
    formData.taskExecutionDuration = minutes
  }
}

// 处理工单完成状态变化
const handleCompletedChange = (checked: boolean) => {
  if (checked) {
    // 如果勾选了"工单已完成"，则所有保养项都标记为完成
    upkeepItems.value.forEach(item => {
      item.isCompleted = true
    })
  }
}

// 修改 handleItemCompleteChange 函数
const handleItemCompleteChange = (item: UpkeepItem) => {
  // 如果某个保养项未完成，则取消全选状态
  if (!item.isCompleted) {
    selectAll.value = false
  }
  // 如果所有保养项都完成了，则勾选全选按钮
  else {
    const allCompleted = upkeepItems.value.every(i => i.isCompleted)
    selectAll.value = allCompleted
  }

  // 更新工单完成状态：只有当所有保养项都完成时才设为完成
  formData.isCompleted = upkeepItems.value.every(i => i.isCompleted)
}

// 获取保养人员列表
const getMaintainerList = async () => {
  try {
    maintainerList.value = await UserApi.getSimpleUserList()
  } catch (error) {
    ElMessage.error('获取保养人员列表失败')
    console.error(error)
  }
}

// 获取保养项列表
const getUpkeepItems = async (upkeepId: number) => {
  try {
    // 调用API接口获取保养项列表
    const items = await UpkeepCategoryApi.getItemsByCatId(upkeepId)
    console.log('获取到的保养项列表:', items)
    // 将返回的数据映射到upkeepItems
    upkeepItems.value = items.map((item: any) => ({
      id: item.itemId,
      itemName: item.itemName,
      itemCode: item.itemCode,
      itemDescription: item.itemDescription || '', // 富文本内容直接使用
      isCompleted: false // 初始化为未完成
    }))
  } catch (error) {
    ElMessage.error('获取保养项列表失败')
    console.error(error)
  }
}

// 打开弹窗方法
const open = async (id: number) => {
  try {
    resetForm()
    taskId.value = id
    // 调用接口查询需要的数据
    const result = await UpkeepTaskApi.getUpkeepTask(id)

    // 填充表单数据
    formData.id = result.id
    formData.assigneerId = result.assigneerId ? result.assigneerId.toString() : ''
    formData.taskReceive_time = result.taskReceiveTime || ''
    formData.jobStartTime = result.jobStartTime || ''
    formData.taskStartTime = result.taskStartTime || ''
    formData.taskEndTime = result.taskEndTime || ''

    // 如果 taskStartTime 为 null，则默认设置为任务接收时间
    formData.taskStartTime = result.taskStartTime || result.taskReceiveTime || ''

    // 如果 taskEndTime 为 null，则默认设置为当前时间
    formData.taskEndTime = result.taskEndTime || Date.now()

    // 设置接收人名称
    const assigneer = maintainerList.value.find(user => user.id === result.assigneerId)
    assigneerName.value = assigneer ? assigneer.nickname : ''

    // 获取保养项列表
    if (result.upkeepId) {
      await getUpkeepItems(result.upkeepId)
    }

    // 如果工时为null，则默认设置为任务结束时间减去任务开始时间
    if (!result.taskExecutionDuration && formData.taskStartTime && formData.taskEndTime) {
      calculateWorkHours()
    }

    // 获取当前用户信息并设置为默认保养人
    const currentUser = await getUserProfile()
    if (currentUser && currentUser.id) {
      formData.assigneerIds = [currentUser.id]
    }

    dialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取任务信息失败')
    console.error('获取任务信息失败:', error)
  }
}


// 修改 handleSubmit 函数，添加保养项校验
const handleSubmit = async () => {
  try {
    submitting.value = true
    await formRef.value?.validate()

    // 验证任务开始和结束时间
    if (formData.taskStartTime && formData.taskEndTime) {
      const startTime = new Date(parseInt(formData.taskStartTime)).getTime()
      const endTime = new Date(parseInt(formData.taskEndTime)).getTime()
      if (startTime >= endTime) {
        ElMessage.error('任务结束时间必须大于任务开始时间')
        submitting.value = false
        return
      }
    }

    // 校验保养项列表，至少勾选一项
    const completedCount = upkeepItems.value.filter(item => item.isCompleted).length
    if (completedCount === 0) {
      ElMessage.error('请至少完成一项保养项')
      submitting.value = false
      return
    }

    // 准备提交数据
    const submitData: UpkeepTaskWorkReport = {
      id: formData.id,
      assigneerId: formData.assigneerId,
      taskReceiveTime: formData.taskReceive_time,
      jobStartTime: formData.jobStartTime,
      taskStartTime: formData.taskStartTime,
      taskEndTime: formData.taskEndTime,
      taskExecutionDuration: formData.taskExecutionDuration,
      assigneerIds: formData.assigneerIds,
      description: formData.description,
      isCompleted: formData.isCompleted, // 仍然提交 isCompleted 状态
      upkeepItems: upkeepItems.value.map(item => ({
        taskId: formData.id,
        itemId: item.id,
        isCompleted: item.isCompleted
      }))
    }

    // 发送请求
    await UpkeepTaskApi.submitWorkReport(submitData)

    ElMessage.success('报工成功')
    emit('success')
    handleClose()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败，请检查表单')
  } finally {
    submitting.value = false
  }
}

// 初始化获取保养人员列表
getMaintainerList()

// 暴露方法给父组件
defineExpose({
  open
})
</script>

<style scoped>
.dialog-footer {
  text-align: right;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.mb-6 {
  margin-bottom: 24px;
}

.text-lg {
  font-size: 16px;
}

.font-medium {
  font-weight: 500;
}

.text-gray-700 {
  color: #4a4a4a;
}

.el-form-item {
  margin-bottom: 16px;
}

.el-checkbox__label {
  font-size: 14px;
  color: #606266;
}

.el-checkbox__input.is-checked .el-checkbox__inner {
  background-color: #008c46;
  border-color: #008c46;
}

.el-checkbox__input.is-checked .el-checkbox__inner::after {
  transform: scale(1.2);
  color: white;
}

:deep(.el-input-number.is-disabled .el-input-number__decrease),
:deep(.el-input-number.is-disabled .el-input-number__increase) {
  display: none;
}
</style>